import { deviceControllerGetDeviceLevelInfo as getDeviceLevelInfo } from '@/services/ess/deviceInfo';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { createContext, useCallback, useContext, useEffect, useState } from 'react';
import { useModel } from 'umi';
import { DeviceTreeDataNode } from './types';

interface ContextType {
  selectedDevice: DeviceTreeDataNode | undefined;
  determinationParameter: { hasArea?: boolean; treeData?: API.DeviceTreeVO[] } | undefined;
  getData: () => Promise<API.DeviceInfo[]>; // 改为函数类型
  deviceInfo: { ts?: string | undefined; onLine?: string | undefined } | undefined;
  isRefesh: boolean;
  setDeviceInfo: (params: { ts?: string | undefined; onLine?: string | undefined }) => void;
  setIsRefesh: (isRefesh: boolean) => void;
  setSelectedDevice: (selectedDevice: DeviceTreeDataNode & { path: string[] }) => void;
  soc: number | undefined;
  setSoc: (soc: number | undefined) => void;
  updateNodeSOC: (nodeId: string, soc: number) => void;
  updateNOdeSelect: (nodeId: string) => void;
}

const SelectedDeviceNodeContext = createContext<ContextType>({
  selectedDevice: undefined,
  determinationParameter: undefined,
  deviceInfo: undefined,
  isRefesh: false,
  getData: async () => [], // 提供一个默认的空函数
  setDeviceInfo: () => {}, // 默认空函数
  setIsRefesh: () => {},
  setSelectedDevice: () => {},
  soc: undefined,
  setSoc: () => {},
  updateNodeSOC: () => {},
  updateNOdeSelect: () => {},
});
const useUpdateNOdeSelect = () => {
  const { updateNOdeSelect } = useContext(SelectedDeviceNodeContext);
  return updateNOdeSelect;
};

const useUpdateNodeSOC = () => {
  const { updateNodeSOC } = useContext(SelectedDeviceNodeContext);
  return updateNodeSOC;
};

const useSOC = () => {
  const { soc, setSoc } = useContext(SelectedDeviceNodeContext);
  return { soc, setSoc };
};

const useSelectedDeviceNode = () => {
  const { selectedDevice } = useContext(SelectedDeviceNodeContext);
  return selectedDevice;
};

const useSetSelectedDevice = () => {
  const { setSelectedDevice } = useContext(SelectedDeviceNodeContext);
  return setSelectedDevice;
};

const useParams = () => {
  const { determinationParameter } = useContext(SelectedDeviceNodeContext);
  return determinationParameter;
};

const useDeviceInfo = () => {
  // 创建一个新的 hook 用于管理 deviceInfo
  const { deviceInfo, setDeviceInfo } = useContext(SelectedDeviceNodeContext);
  return { deviceInfo, setDeviceInfo };
};

const useIsFresh = () => {
  // 创建一个新的 hook 用于管理 deviceInfo
  const { isRefesh, setIsRefesh } = useContext(SelectedDeviceNodeContext);
  return { isRefesh, setIsRefesh };
};

// 获取设备树数据的函数
const useGetDeviceTreeData = () => {
  const { initialState } = useModel('@@initialState');
  const { selectedDevice } = useContext(SelectedDeviceNodeContext);

  // 使用 useCallback 缓存 getData 函数
  const getData = useCallback(async () => {
    const res = await getDeviceLevelInfo({
      stationId: initialState?.stationId,
      areId: selectedDevice?.areaId ?? undefined,
    });

    const combinedTree: API.DeviceInfo[] = [
      ...(res?.data?.areaInfos.map((res) => ({
        name: res?.areaName,
        code: res?.id,
        children: [],
        isArea: true,
      })) ?? []),
      ...(res?.data?.deviceClusterInfos ?? []),
      ...(res?.data?.deviceBoxInfos ?? []),
      ...(res?.data?.deviceBmsInfos ?? []),
    ];

    const hasArea = initialState?.isArea;
    const nodeMapping = {};
    for (const node of combinedTree) {
      node.children = [];
      nodeMapping[node.id] = node;
    }

    let tree: API.DeviceInfo[] = [];

    combinedTree.forEach((node) => {
      if (node.parentId === 0) {
        tree.push(node);
      } else if (nodeMapping[node.parentId]) {
        nodeMapping[node.parentId].children.push(node);
      }
    });

    const AreaArray = combinedTree.filter((node) => {
      return node?.isArea ? node : null;
    });

    for (let areaNode of AreaArray) {
      areaNode.children = []; // 清空 children 数组
      for (let node of tree) {
        if (node?.areaId === areaNode?.code) {
          areaNode?.children.push(node);
        }
      }
    }

    return hasArea ? AreaArray : tree;
  }, [initialState?.stationId, selectedDevice?.areaId]);

  return getData;
};

interface Item {
  label: string;
  value: string | number;
  remark?: string;
}
//一些常用的字典做相应的导出
const useDict = () => {
  const [runState, setrunState] = useState<Item[]>([]);
  const [onlineState, setOnlineState] = useState<Item[]>([]);
  const [chargeDischargeStatusOptions, setChargeDischargeStatusOptions] = useState<Item[]>([]);
  useEffect(() => {
    const fetchOnlineState = async () => {
      try {
        const result = await fetchDictInfo(DATABASE_TYPE_ENUM.ONLINE_STATUS);
        setOnlineState(result || []);

        let ChargeStatus = await fetchDictInfo(DATABASE_TYPE_ENUM.CHARGE_STATUS);
        setChargeDischargeStatusOptions(ChargeStatus || []);

        // 运行状态字典
        let runstates = (await fetchDictInfo(DATABASE_TYPE_ENUM.PCS_STATUS)) || [];
        setrunState(runstates || []);
      } catch (error) {
        console.error('Failed to fetch online state:', error);
        // 可以在这里设置一个错误状态如果需要
      }
    };

    fetchOnlineState();
  }, []); // 空依赖数组意味着这个效果只在组件挂载时运行一次

  return {
    onlineState,
    chargeDischargeStatusOptions,
    runState,
  };
};

export {
  SelectedDeviceNodeContext,
  useSelectedDeviceNode,
  useParams,
  useGetDeviceTreeData,
  useDict,
  useDeviceInfo,
  useIsFresh,
  useSetSelectedDevice,
  useSOC,
  useUpdateNodeSOC,
  useUpdateNOdeSelect,
};
